<template>
	<view class="search" v-click-outside="inputBlur">
		<view class="inputVal">
			<view class="searchBorder" :class="focus ? 'inputFocus' : ''">
				<text class="uicon-search u-iconfont"></text>
				<input @focus="focus = true" v-model="searchValue" placeholder="请输入关键词" />
			</view>

			<view v-if="searchValue && focus" class="list">
				<m-link :url="web.url" v-for="(web, index) of dataList" :key="index">
					<view class="item" v-if="containStr(web.title, searchValue)">
						<image :src="web.logo"></image>
						<!-- App端（vue页面V3编译模式）和H5端支持v-html，其他端不支持v-html。 -->
						<view v-html="searchVal(web.title)"></view>
					</view>
				</m-link>
			</view>
		</view>
	</view>
</template>

<script>
import { mapState } from 'vuex';

export default {
	data() {
		return {
			focus: false,
			searchValue: ''
		};
	},
	computed: {
		...mapState({
			dataList: state => state.global.searchList
		}),
		// 传入原串和匹配值
		containStr() {
			return function(str, matchStr) {
				return new RegExp(matchStr, 'i').test(str);
			};
		}
	},
	methods: {
		searchVal(text) {
			text = text.replace(this.searchValue, "<text style='color:red;'>" + this.searchValue + '</text>');
			return text;
		},
		inputBlur() {
			this.focus = false;
		}
	}
};
</script>

<style lang="scss" scoped>
.search {
	.inputVal {
		position: relative;

		.searchBorder {
			display: flex;
			align-items: center;
			border: 1px solid #2c2e2f;
			padding: 6px 8px;
			background-color: #2c2e2f;

			text {
				font-size: 20px;
				color: rgb(160, 148, 146);
			}

			input {
				margin-left: 10px;
				color: #fff;
				line-height: 1;
			}
		}

		.inputFocus {
			border-color: #ffffff;
		}

		.list {
			height: 320px;
			overflow-y: auto;
			border: 1px solid #c4c7ce;
			width: 100%;
			position: absolute;
			background-color: #fefefe;
			z-index: 999;
			color: #000;
			.item {
				font-size: 14px;
				text-align: left;
				padding: 10px 0;
				padding-left: 20px;
				border-bottom: 1px solid #eeeeee;
				display: flex;
				align-items: center;

				&:hover {
					background-color: rgba($color: #000000, $alpha: 0.4);
					color: #fefefe;
				}

				image {
					width: 20px;
					height: 20px;
					padding-right: 20px;
				}
			}
		}
	}
}
</style>
